package com.controller;

import com.model.UserModel;
import com.services.impl.UserServicesImpl;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Program: exam
 * @ClassName: ChangeStatusServletController
 * @Description: 更改用户的状态，拉黑，可用
 * @Author: li
 * @Create: 2019-07-23 16:37
 */
@WebServlet("/ChangeStatusServlet")
public class ChangeStatusServletController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应格式
        response.setContentType("application/json;charset=UTF-8");
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");

        Map<String, Object> result = new HashMap<>();
        
        try {
            String email = request.getParameter("email");
            int status = Integer.parseInt(request.getParameter("status"));
            
            // 参数校验
            if (email == null || email.trim().isEmpty()) {
                result.put("code", 400);
                result.put("msg", "参数错误：email不能为空");
                response.getWriter().write(JSONObject.fromObject(result).toString());
                return;
            }

            // 打印日志
            System.out.println("修改用户状态 - email: " + email + ", status: " + status);

            // 调用服务层
            UserServicesImpl userServices = new UserServicesImpl();
            userServices.changStatus(email.trim(), status);
            
            // 查询更新后的用户状态进行验证
            UserModel userModel = userServices.queryUserInfoByEmail(email.trim());
            if (userModel != null) {
                result.put("code", 0);
                result.put("msg", status == 1 ? "启用成功" : "拉黑成功");
                result.put("data", userModel);
            } else {
                result.put("code", 500);
                result.put("msg", "状态更新失败：数据库更新未生效");
            }
            
        } catch (Exception e) {
            e.printStackTrace(); // 打印详细错误信息
            result.put("code", 500);
            result.put("msg", "状态修改失败：" + e.getMessage());
        }
        
        String jsonResult = JSONObject.fromObject(result).toString();
        System.out.println("响应结果：" + jsonResult);
        response.getWriter().write(jsonResult);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
